package com.rivercloud.controller;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.filter.CheckSession;

import com.rivercloud.dao.ExcelDAO;
import com.rivercloud.dao.TableColDao;
import com.rivercloud.dao.TableDao;
import com.rivercloud.dao.TemplateColDao;
import com.rivercloud.dao.TemplateDao;
import com.rivercloud.dao.UserDao;
import com.rivercloud.dao.Impl.TableColDaoImpl;
import com.rivercloud.dao.Impl.TableDaoImpl;
import com.rivercloud.dao.Impl.TemplateColDaoImpl;
import com.rivercloud.dao.Impl.TemplateDaoImpl;
import com.rivercloud.dao.Impl.UserDaoImpl;
import com.rivercloud.entity.ExcelTable;
import com.rivercloud.entity.Project;
import com.rivercloud.entity.TableCol;
import com.rivercloud.entity.Template;
import com.rivercloud.entity.TemplateCol;
import com.rivercloud.entity.User;

@Filters(@By(type=CheckSession.class, args={"user", "/login.jsp"}))  
@At("/tpl")
@Fail("http:500")
public class TemplateController {
	@Inject
	private ExcelDAO excelDAO = new ExcelDAO();
	@Inject
	private TemplateDao templateDao = new TemplateDaoImpl();
	@Inject
	private TemplateColDao templateColDao = new TemplateColDaoImpl();
	@Inject
	private TableDao tableDao = new TableDaoImpl();
	@Inject
	private TableColDao tableColDao = new TableColDaoImpl();
	private UserDao userDao = new UserDaoImpl();
	
	
	//检验模板名是否可用
	@At("/checkTemplateName")
	public void checkTemplateName(HttpServletRequest request,HttpServletResponse response) {
		try {
			String templateName = request.getParameter("templateName");
			Template existTemplate = templateDao.checkTemplateName(templateName);
			if(existTemplate == null){
				response.getWriter().print("1");
			}else{
				response.getWriter().print("2");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	
	}
	
	
	@At("/toTable")
/*	@Ok("jsp:jsp.tableInfo")*/
	public void toTable(HttpServletRequest request,HttpServletResponse response){
		try {
			int templateId = Integer.parseInt(request.getParameter("templateId"));
			int projectId = Integer.parseInt(request.getParameter("projectId"));
			int userId = Integer.parseInt(request.getParameter("userId"));
			User user = userDao.findUserById(userId);
			String creator = user.getName();
			
			String tableName = request.getParameter("tableName");
			ExcelTable excelTable = new ExcelTable();
			excelTable.setTableName(tableName);
			excelTable.setProjectId(projectId);
			excelTable.setUserId(userId);
			excelTable.setCreator(creator);
			
			
			tableDao.addTable(excelTable);
			int tableId = tableDao.lastInsertId();
			
			List<TableCol> tableColList = new ArrayList<>();
			List<TemplateCol> templateColList = 
					templateColDao.findByTemplateId(templateId);
			for (TemplateCol templateCol : templateColList) {
				TableCol tableCol = new TableCol();
				tableCol.setColName(templateCol.getColName());
				tableCol.setColNum(templateCol.getColNum());
				tableCol.setColType(templateCol.getColType());
				tableCol.setDefVal(templateCol.getDefVal());
				tableCol.setTableId(tableId);
				tableColDao.addTableCol(tableCol);
				tableColList.add(tableCol);
			}
			request.setAttribute("tableId", tableId);
			request.setAttribute("excelTable", excelTable);
			request.setAttribute("tableColList", tableColList);
			response.getWriter().print(tableId);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	@At("/toTemplate")
	@Ok("jsp:jsp.template")
	public void toTemplate(HttpServletRequest request){
		try {
			int tableId = Integer.parseInt(request.getParameter("tableId"));
			int creator = Integer.parseInt(request.getParameter("userId"));
			String templateName = request.getParameter("templateName");
			Template template = new Template();
			template.setTemplateName(templateName);
			template.setCreator(creator);
			templateDao.addTemplate(template);
			int templateId = templateDao.fingIdByName(templateName);
			
			
			List<TemplateCol> templateColList = new ArrayList<>();
			List<TableCol> tableColList = tableColDao.findByTableId(tableId);
			for (TableCol tableCol : tableColList) {
				TemplateCol templateCol = new TemplateCol();
				
				templateCol.setColName(tableCol.getColName());
				templateCol.setColNum(tableCol.getColNum());
				templateCol.setColType(tableCol.getColType());
				templateCol.setDefVal(tableCol.getDefVal());
				templateCol.setTemplateId(templateId);
				templateColDao.addTemplateCol(templateCol);
				templateColList.add(templateCol);
			}
		
			request.setAttribute("template", template);
			request.setAttribute("templateColList", templateColList);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	@At("/createTemplate2")
	/*@Ok("redirect:/tpl/templateList")*/
	public void createTemplate2(HttpServletRequest request,HttpServletResponse response) {
		
		Template template = new Template();
		
		String templateName = request.getParameter("templateName");
		int userId = Integer.parseInt(request.getParameter("userId"));
		int totalNumber = Integer.parseInt(request.getParameter("totalNumber"));
		Map<String, String[]> map = request.getParameterMap();

		
		try {
			List<TemplateCol> templateColList = new ArrayList<>();
			Class c = TemplateCol.class;
			Field[] fields = c.getDeclaredFields();
			Field.setAccessible(fields, true);
			template.setTemplateName(templateName);
			template.setCreator(userId);
			
			templateDao.addTemplate(template);
			int templateId = templateDao.fingIdByName(templateName);
			for (int i = 0; i < totalNumber; i++) {
				TemplateCol templateCol = new TemplateCol();
				templateCol.setColNum(i + 1);
				templateCol.setTemplateId(templateId);
				int flag = 0;
				for (int j = 0; j < fields.length; j++) {
					Field field = fields[j];
					String name = field.getName();
					if (!name.equals("createTime")) {
						Constructor<?> constructor = field.getType().getConstructor(String.class);
						String parameter = request.getParameter(name + (i + 1));
						if (parameter != null && !"".equals(parameter)) {
							flag++;
							field.set(templateCol, constructor.newInstance(parameter));
						}
					}
				}
				if (flag != 0) {
					
					templateColList.add(templateCol);
					templateColDao.addTemplateCol(templateCol);
				}
			}
			System.out.println(templateColList.size());
			for (TemplateCol li : templateColList) {
				System.out.println(li);
			}
			response.getWriter().print(templateId);
			
			
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}
	
	

	@At("/createTemplate")
	@Ok("redirect:/tpl/templateList")
	public void createTemplate(HttpServletRequest request) {

		Template template = new Template();

		String templateName = request.getParameter("templateName");
		int userId = Integer.parseInt(request.getParameter("userId"));

		Map<String, String[]> map = request.getParameterMap();
		System.out.println(map.size());

		try {
			List<TemplateCol> templateColList = new ArrayList<>();
			Class c = TemplateCol.class;
			Field[] fields = c.getDeclaredFields();
			Field.setAccessible(fields, true);
			template.setTemplateName(templateName);
			template.setCreator(userId);

			templateDao.addTemplate(template);
			int templateId = templateDao.fingIdByName(templateName);
			for (int i = 0; i < (map.size() - 1) / 3; i++) {
				TemplateCol templateCol = new TemplateCol();
				templateCol.setColNum(i + 1);
				templateCol.setTemplateId(templateId);
				int flag = 0;
				for (int j = 0; j < fields.length; j++) {
					Field field = fields[j];
					String name = field.getName();
					if (!name.equals("createTime")) {
						Constructor<?> constructor = field.getType().getConstructor(String.class);
						String parameter = request.getParameter(name + (i + 1));
						if (parameter != null && !"".equals(parameter)) {
							flag++;
							field.set(templateCol, constructor.newInstance(parameter));
						}
					}
				}
				if (flag != 0) {

					templateColList.add(templateCol);
					templateColDao.addTemplateCol(templateCol);
				}
			}
			System.out.println(templateColList.size());
			for (TemplateCol li : templateColList) {
				System.out.println(li);
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}
	
	
	@At("/template")
	@Ok("jsp:jsp.template")
	public void template(HttpServletRequest request){
		try {
			int templateId = Integer.parseInt(request.getParameter("templateId"));
			Template template = templateDao.findTemplateById(templateId);
			List<TemplateCol> templateColList = 
					templateColDao.findByTemplateId(templateId);
			
			request.setAttribute("template", template);
			request.setAttribute("templateColList", templateColList);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@At("/showTemplate")
	@Ok("jsp:jsp.showTemplate")
	public void showTemplate(HttpServletRequest request){
		try {
			int templateId = Integer.parseInt(request.getParameter("templateId"));
			Template template = templateDao.findTemplateById(templateId);
			List<TemplateCol> templateColList = 
					templateColDao.findByTemplateId(templateId);
			
			request.setAttribute("template", template);
			request.setAttribute("templateColList", templateColList);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 获取所有模板
	@At("/templateList")
	@Ok("jsp:jsp.templateList")
	public void templateList(HttpServletRequest request) {
		List<Template> templateList = templateDao.findAll();
		request.setAttribute("templateList", templateList);
	}
	
	@At("/addTemplate")
	@Ok("jsp:jsp.createTemplate2")
	public void addTemplate(HttpServletRequest request) {
		
	}
	
	@At("/addTable")
	@Ok("jsp:jsp.addTable")
	public void addTable(HttpServletRequest request) {
		List<Template> templateList = templateDao.findAll();
		request.setAttribute("templateList", templateList);
	}
	
	@At("/addTemplateDesc")
	@Ok("json")
	public Map addTemplateDesc(HttpServletRequest request) {
		try {
			String tid = request.getParameter("templateId");
			String templateDesc = request.getParameter("templateDesc");
			Integer templateId = Integer.parseInt(tid);
			Map map = new HashMap();
			
			
			
			templateDao.addTemplateDesc(templateId,templateDesc);
			map.put("true", true);
			return map;
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	

}
